package com.tiecode.pastejava

import android.graphics.drawable.Drawable
import com.rapid.api.component.widget.editor.Editor
import com.rapid.api.ext.plugin.AndroidPlugins
import com.rapid.api.framework.domain.editor.BaseEditorMenuAction
import com.rapid.util.android.ContentUtils
import com.rapid.util.android.ContextUtils
import com.tiecode.compiler.api.Compiler
import com.tiecode.compiler.api.plugin.CompilerPlugin
import com.tiecode.compiler.api.process.Elements
import com.tiecode.compiler.toolchain.CompilerPlugins

class PasteJavaMenuAction : BaseEditorMenuAction() {
    private var elements: Elements? = null

    init {
        CompilerPlugins.assemble(object : CompilerPlugin {
            override fun apply(arg: Compiler?) {
                elements = arg?.context?.elements
            }
        })
    }

    override fun perform(editor: Editor) {
        val localElements = elements ?: return
        ContentUtils.getClipboardText(applicationContext)?.let {
            val converter = JavaCodeConverter(
                localElements,
                0
            )
            editor.paste(converter.convert(it))
        }
    }

    override fun getId(): String = "pasteJava"

    override fun getTitle(): String = "粘贴Java代码"

    override fun getIcon(): Drawable {
        val context = AndroidPlugins.getContext(this)
        return ContextUtils.getDrawable(context, R.drawable.ic_paste_java)
    }

    override fun isEnabled(editor: Editor?): Boolean {
        return "cn.tiecode.android" == projectFramework.activeManager.identifier
    }
}